package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;


    @Value("${sky.shop.address}")
    private String address;

    @Value("${sky.baidu.ak}")
    private String ak;

    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //下订单的逻辑
        //首先判断可能会出的错误，有错报错，无错继续
        //地址信息可能为空，点的菜品可能为空
        Long currentId = BaseContext.getCurrentId();

        AddressBook addressBookMapperById = addressBookMapper.findById(ordersSubmitDTO.getAddressBookId());
        if(addressBookMapperById==null)
            throw new ShoppingCartBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);

        List<ShoppingCart> getcarts = shoppingCartMapper.getcarts(currentId);
        if (getcarts==null &&getcarts.size()==0)
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        //然后将订单信息插入订单表
       String address= addressBookMapperById.getCityName()+addressBookMapperById.getDistrictName()+addressBookMapperById.getDetail();
        checkOutOfRange(address);


        Orders orders=new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(currentId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(addressBookMapperById.getPhone());
        orders.setAddress(addressBookMapperById.getDetail());
        orders.setUserName(addressBookMapperById.getConsignee());
        orders.setConsignee(addressBookMapperById.getConsignee());

        orderMapper.insert(orders);
        //将订单信息插入订单明细中，一个订单可以有多个明细信息，一个明细表对应一个订单，1：N的形式
        List<OrderDetail>orderDetails=new ArrayList<>();

        for (ShoppingCart getcart : getcarts) {
            OrderDetail orderDetail=new OrderDetail();
            BeanUtils.copyProperties(getcart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        orderMapper.insertDetails(orderDetails);
        //清空购物车
        shoppingCartMapper.delete(currentId);
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .orderTime(orders.getOrderTime())
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();


        return orderSubmitVO;
    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
        JSONObject jsonObject=new JSONObject();
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);


        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
        Map map=new HashMap();
        map.put("type",1);
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号: "+outTradeNo);

        String json= JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);


    }

    @Override
    public OrderVO selectById(Long id) {

        Orders order = orderMapper.selectByOrderId(id);
        OrderVO orderVO=new OrderVO();
        BeanUtils.copyProperties(order,orderVO);
        List<OrderDetail> orderDetails = orderMapper.selectDetailByOrderId(id);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    @Override
    public PageResult selectPageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Long currentId = BaseContext.getCurrentId();
        ordersPageQueryDTO.setUserId(currentId);
        List<Orders> orders = orderMapper.selectById(ordersPageQueryDTO);
        Page<Orders> page=(Page<Orders>)orders;

        List<OrderVO>orderVOS=new ArrayList<>();
        for (Orders order : orders) {
            OrderVO orderVO=new OrderVO();
            Long id = order.getId();
            BeanUtils.copyProperties(order,orderVO);
            List<OrderDetail> orderDetails = orderMapper.selectDetailByOrderId(id);
            orderVO.setOrderDetailList(orderDetails);
            orderVOS.add(orderVO);
        }

        //检查数据库中的订单如果从下单到现在超过时间15分钟，则将状态从待支付
        List<Orders> orders1 = orderMapper.selectByUserId(BaseContext.getCurrentId());
        for (Orders orders2 : orders1) {
            long minutes = Duration.between(orders2.getOrderTime(), LocalDateTime.now()).toMinutes();
            if (minutes>=15&&orders2.getStatus()==1)
                orderMapper.updateStatus(orders2.getId());
        }



        PageResult pageResult=new PageResult(page.getTotal(),orderVOS);
        return pageResult;
    }

    @Override
    public void cancel(Long id) {
        Orders orders = orderMapper.selectByOrderId(id);
        if (orders.getStatus()==2){
            //取消的订单已经付过钱了，所以这里需要有一个退款逻辑
            //************
            //退完款之后修改订单状态2->6
            orderMapper.updateStatus(id);
        }
        else {
            orderMapper.updateStatus(id);
        }

    }

    @Override
    public void anotherOne(Long id) {
        Orders build = Orders.builder()
                .id(id)
                .orderTime(LocalDateTime.now())
                .status(1)
                .build();
        orderMapper.update(build);

        //orderMapper.updateStatusToOne(id);
    }

    @Override
    public PageResult AdminPageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        List<Orders> orders = orderMapper.selectById(ordersPageQueryDTO);
        Page<Orders> page=(Page<Orders>)orders;

        List<OrderVO>orderVOS=new ArrayList<>();
        for (Orders order : orders) {
            OrderVO orderVO=new OrderVO();
            Long id = order.getId();
            BeanUtils.copyProperties(order,orderVO);
            List<OrderDetail> orderDetails = orderMapper.selectDetailByOrderId(id);
            orderVO.setOrderDetailList(orderDetails);
            orderVOS.add(orderVO);
        }

        //检查数据库中的订单如果从下单到现在超过时间15分钟，则将状态从待支付
        List<Orders> orders1 = orderMapper.selectByUserId(BaseContext.getCurrentId());
        for (Orders orders2 : orders1) {
            long minutes = Duration.between(orders2.getOrderTime(), LocalDateTime.now()).toMinutes();
            if (minutes>=15&&orders2.getStatus()==1) {
                //orderMapper.updateStatus(orders2.getId());
                orders2.setCancelTime(LocalDateTime.now());
                orders2.setCancelReason("订单超时，自动取消");
                orders2.setStatus(Orders.CANCELLED);
                orderMapper.update(orders2);
            }
        }

        PageResult pageResult=new PageResult(page.getTotal(),orderVOS);
        return pageResult;
    }

    @Override
    public OrderStatisticsVO statistics() {
        /*1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
        * 待派送数量  3
format: int32

├─ deliveryInProgress	integer	必须		派送中数量  4
format: int32

├─ toBeConfirmed	integer	必须		待接单数量  2
        * */
        OrderStatisticsVO orderStatisticsVO=new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(orderMapper.selectTwo());
        orderStatisticsVO.setConfirmed(orderMapper.selectThree());
        orderStatisticsVO.setDeliveryInProgress(orderMapper.selectFour());
        return orderStatisticsVO;
    }

    @Override
    public void receive(OrdersConfirmDTO ordersConfirmDTO) {
        orderMapper.receive(ordersConfirmDTO);
    }

    @Override
    public void send(Long id) {
        orderMapper.send(id);
    }

    @Override
    public void complete(Long id) {
        LocalDateTime now = LocalDateTime.now();
        orderMapper.complete(id,now);
    }

    @Override
    public void reject(OrdersRejectionDTO ordersRejectionDTO) {
        LocalDateTime now = LocalDateTime.now();
        Orders build = Orders.builder()
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .id(ordersRejectionDTO.getId())
                .cancelTime(now)
                .status(Orders.CANCELLED)
                .build();
        orderMapper.update(build);
    }

    @Override
    public void adminCancel(OrdersCancelDTO ordersCancelDTO) {
        Orders build = Orders.builder()
                .status(Orders.CANCELLED)
                .cancelTime(LocalDateTime.now())
                .cancelReason(ordersCancelDTO.getCancelReason())
                .id(ordersCancelDTO.getId())
                .build();
        orderMapper.update(build);
    }

    @Override
    public void remind(Long id) {
        Orders orders = orderMapper.selectByOrderId(id);
        if (orders==null)throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        Map map=new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号: "+orders.getNumber());

        String json= JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }


    /**
     * 检查客户的收货地址是否超出配送范围
     * @param
     */
    private void checkOutOfRange(String Useraddress) {
        Map map = new HashMap();
        map.put("address",address);
        map.put("output","json");
        map.put("ak",ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address",Useraddress);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }

}
